/**
 * 积分商城-商品详情
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    hashHistory,
    Link
} from 'react-router'

import Header from './Common/Header'
import {
    HttpService,
    dateFormat,
    Tips
} from '../Tools'

import '../Plugins/swiper/css/swiper.css'
import '../Plugins/swiper/js/swiper.jquery.min.js'

import imgErr from '../Img/other/splitGraphBig.png'
import imgErr2 from '../Img/other/splitImg.jpg'
import logo from '../Img/mall/product02.png'
import ConfirmBox from './Common/ConfirmBox'

export default class ProductDetails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: 0,
            data: {},
            moreCompany: [],
            jfGoodsArchives: {}
        }
        this.config = {
            title: '温馨提示'
        };
    }

    componentWillMount() {
        this.getDetail()
    }

    //获取详情
    getDetail() {
        HttpService.query({
            url: '/jf/goodsArchives/getJfGoodsArch',
            // url: '/src/data/integralGoodDetail.json',
            data: {
                token: sessionStorage.appToken,
                goodsArchId: this.props.params.id
            },
            async:false,
            success: (res => {
                this.getMoreCompany();
                if (res.code == 10140) {
                    let url = imgErr
                    if (res.data.jfGoodsArchives.smallImg.indexOf('{') > -1)
                        url = JSON.parse(res.data.jfGoodsArchives.smallImg).goodsDetailsImg
                    if (res.data.jfGoodsArchives.actualNum == 0)
                        Tips('该商品已全部兑换')
                    this.setState({
                        data: res.data,
                        jfGoodsArchives: res.data.jfGoodsArchives,
                        url
                    })
                }
            })
        })
    }



    /**
     * 关闭confirmBox
     */
    cfmCancel() {
        this.setState({
            show: 0
        });
    }

    /**
     * 确定
     * @returns {XML}
     */
    cfmSure() {
        this.setState({
            show: 0
        });
        if (this.config.sureName == '查看详情') {
            hashHistory.push(`/MyPackage`)
            _hmt.push(['_trackEvent', 'page', 'ProductDetails', '商品兑换成功']);
            return
        }
        _hmt.push(['_trackEvent', 'page', 'ProductDetails', '商品兑换']);

        let data = {
            token: sessionStorage.appToken,
            goodsArchId: this.props.params.id,
            num: 1
        }
        if (sessionStorage.userrole == '家长')
            data.babyId = sessionStorage.babyid
        HttpService.query({
            url: '/jf/goodsArchives/getGoods',
            data,
            async: false,
            success: (res => {
                if (res.code == 50006) {
                    this.config.content = '兑换成功'
                    this.config.cancelName = '确定'
                    this.config.sureName = '查看详情'
                    this.setState({
                        show: 1
                    });
                } else {
                    Tips(res.data)
                    _hmt.push(['_trackEvent', 'page', 'ProductDetails', '商品兑换失败']);
                }
            })
        })
    }

    //更多优惠-商家展示
    getMoreCompany() {
        let data = {
            token:sessionStorage.appToken,
            page: 1,
            size: 6,
            range: sessionStorage.userrole == '家长' ? 2 : 1
        };
        if (sessionStorage.userrole == '家长' && sessionStorage.babyid)
            data.babyid = sessionStorage.babyid
        HttpService.query({
            url: '/jf/company/pageJfCompanyArchOnly',
            data,
            success: (res => {
                if (res.code == 10140) {
                    this.setState({
                        moreCompany: res.data.list
                    });
                    //swiper
                    var swiper = new Swiper('.swiper-container', {
                        slidesPerView: 3.7,
                        spaceBetween: 24,
                        freeMode: true,
                        pagination: {
                            // el: '.swiper-pagination',
                            clickable: true,
                        },
                    });
                }
            })
        })
    }


    /**
     * 点击兑换
     * @returns {XML}
     */
    exchange() {
        this.config.content = '是否继续兑换？'
        this.config.cancelName = '取消'
        this.config.sureName = '确定'
        this.setState({
            show: 1
        });
    }

    //图片地址错误
    imgErr(imgErr,e) {
        e.currentTarget.setAttribute('src', imgErr)
    }
    render() {
        const {
            show,
            url,
            data,
            moreCompany,
            jfGoodsArchives,
        } = this.state

        let unit = sessionStorage.userrole == '家长' ? '积分' : '荣誉值';
        const moreCompanyTag = moreCompany.map(item => {
            return (
                <li className="swiper-slide">
                    <Link className='item' to={`/companyInfo/${item.id}`}>
                        <img src={item.logo} onError={this.imgErr.bind(this,imgErr2)} />
                        <p>{item.name}</p>
                    </Link>
                </li>
            )
        })
        return (
            <div className="product_details">
                <Header title="商品详情" />
                <div className="product_img">
                    <img src={url} onError={this.imgErr.bind(this,imgErr)} />
                    <div className='others'>
                        <p><span>{data.companyName}</span>{jfGoodsArchives.name}</p>
                        <p>价值{jfGoodsArchives.price}元</p>
                    </div>
                </div>
                {jfGoodsArchives.goodsPackage?<div className="pdtlinfo">
                    <p className='title'>套餐内容</p>
                    <ul className='ctncontent'>
                        {
                            JSON.parse(jfGoodsArchives.goodsPackage).map((item)=>{
                                return (
                                    <li>
                                        <span className='name'>{item.name}（{item.number}份）</span>
                                        <span className='value'>{item.price}元</span>
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>:null}
                {jfGoodsArchives.contents?<Link className='cinfomorebar cinfomorebar2' to={`/ProductMore/${jfGoodsArchives.id}`}>查看图文详情</Link>:null}
                <div className="pdtlinfo">
                    <p className='title'>购买须知</p>
                    <div className='lists'>
                        <p>有效期</p>
                        <ul>
                            <li>
                                {dateFormat(new Date(jfGoodsArchives.beginTime),'-',false)}
                                至
                                {dateFormat(new Date(jfGoodsArchives.endTime),'-',false)}
                                {jfGoodsArchives.validRemark?
                                    <span>({jfGoodsArchives.validRemark})</span>:null
                                }
                            </li>
                        </ul>
                        {jfGoodsArchives.useTime?[<p>使用时间</p>,
                        <ul>
                            <li>
                                <span>
                                    {jfGoodsArchives.useTime.replace(/\s/g,'').split('&')[0].replace('—','~')}
                                    {jfGoodsArchives.useTime.replace(/\s/g,'').split('&')[1]?<w>({jfGoodsArchives.useTime.replace(/\s/g,'').split('&')[1]})</w>:null}</span>
                            </li>
                        </ul>]:null}
                        {
                            jfGoodsArchives.instructions?[<p>使用规则</p>,
                        <ul>
                                {jfGoodsArchives.instructions.split('<br />').map((item)=>{
                                    return <li>{item}</li>
                                })}
                        </ul>]:null}
                    </div>
                </div>
                <div className='adtelstr adtelstr2 bgc-white'>
                    <Link className='add overhidden' to={`/position/`+encodeURIComponent(escape(data.companyName))+`/${encodeURIComponent(escape(data.address.split('-')[3]))}/${data.address.split('-')[4]}/${data.address.split('-')[5]}`}>
                        <h5>{data.companyName}</h5>
                        <p className='text-els'>
                            {
                                data.address?data.address.split('-').map((item,index)=>{
                                    if(index<4)
                                    return item
                                }):null
                            }
                        </p>
                    </Link>
                    <a className='tel' href={`tel:${data.linkPhone}`} />
                </div>
                {moreCompany.length>0?
                    <div className='cinfointegral'>
                    <div className='bar'>
                        <span>小伙伴们还喜欢</span>
                    </div>
                    <div className="swiper-container morecompany">
                        <ul className='clearfix swiper-wrapper'>
                            {moreCompanyTag}
                        </ul>
                    </div>
                </div>:null}
                <div className="footer_bottom"></div>
                {jfGoodsArchives.actualNum==0?null:
                <div className="product_pay ">
                    <div className="price_left price">
                        <span className="title">{unit}:</span>
                        <span className="number all_punkte">{jfGoodsArchives.consumeCredit}</span>
                    </div>
                    <span className="buttom" onClick={this.exchange.bind(this)}>立即兑换</span>
                </div>}
                <ConfirmBox config={this.config} show={show} cancel={this.cfmCancel.bind(this)} sure={this.cfmSure.bind(this)}/>
            </div>
        )
    }
}
